// 封装请求
import axios from 'axios'
import { Message } from 'element-ui'
// 请求
const http = axios.create({
  baseURL: 'apis',
  timeout: 6000
})

// 请求拦截
http.interceptors.request.use(config => {
  // 请求头设置
  let token = localStorage.getItem('token') || ''
  config.headers.Authorization = token
  return config
}, err => {
  // console.log(err)
  Promise.reject(err)
})

// 响应拦截
http.interceptors.response.use(res => {
  // console.log(res)
  let typeStr = ''
  // 对响应码的处理
  switch (res.status) {
    case 200:
    case 201:
    case 204:
      typeStr = 'success'
      break
    case 400:
    case 401:
    case 403:
    case 404:
    case 422:
      typeStr = 'warning'
      break
    case 500:
      typeStr = 'error'
      break
  }
  Message({
    message: res.data.message === '' ? '请求成功' : res.data.message,
    type: typeStr
  })
  return Promise.resolve(res.data)
}, err => {
  // console.log(err)
  Promise.reject(err)
})

// 返出
export default http
